<?php
declare (strict_types=1);

namespace app\command;

use app\lib\StringUtils;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

class AppInitialization extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('app-init')
            ->setDescription('the app-init command');
    }

    protected function generateEnvData($envFile)
    {
        $envData = [
            'APP_DEBUG' => 'false',
            'TRIGGER_SQL' => 'true',
            'ADMIN_ENTRY' => StringUtils::instance()->generateRandString(16),
            'key' => StringUtils::instance()->generateRandString(32)
        ];
        $matchData = [];
        $replaceData = [];
        foreach ($envData as $key => $envDatum) {
            $envConfig = "";
            preg_match("/{$key} = (.+)/", $envFile, $envConfig);
            $matchData[] = $envConfig[0];
            $replaceData[] = $key . " = " . $envDatum;
        }
        $envFile = str_replace($matchData, $replaceData, $envFile);
        return $envFile;
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $output->writeln('app-init');
        $envFile = null;
        $envPath = root_path() . '/.env';
        try {
            $envFile = file_get_contents(root_path() . '/.env');
        } catch (\Exception $exception) {
            $envFile = file_get_contents(root_path() . '/.example.env');
        }
        file_put_contents($envPath, $this->generateEnvData($envFile));
    }
}
